<?php

function menulink($text, $url = '#', $htmlOptions = array(), $condition = true){

    $icon = '';
    // icon definition
    if(substr($text, 0, 1) == '!'){
        $text = explode(' ', $text, 2);
        $icon = substr($text[0], 1);

        $icon = '<i class="icon-'.$icon. '"></i> ';

        $text = $text[1];
    }

    $li ='<li>';
    if(isMenuActive(array(trim($url[0], '/'))))
        $li = '<li class="active">';

    return $condition ? $li. CHtml::link($icon . $text, $url, $htmlOptions) . ' </li>' : '';

}

function activeWhen(){

    echo isMenuActive(func_get_args()) ? 'active' : '';

}

function collapsedWhen(){

    echo isMenuActive(func_get_args()) ? 'collapsed' : '';

}

function openedWhen(){

    echo isMenuActive(func_get_args()) ? 'opened' : '';

}

function isMenuActive($routes){

    $module = isset(Yii::app()->controller->module) ? Yii::app()->controller->module->getName() : null;

    foreach ($routes as $route){

        if(strpos($route, '/') !== false){
            if($route == Yii::app()->controller->route){
                return true;
            }
        }else if($route == Yii::app()->controller->id || $route == $module){
            return true;
        }

        $route = explode('/', $route);
        $route = $route[0];
        if($route == Yii::app()->controller->id || $route == $module){
            return true;
        }

    }
    return false;
}